<template>
  <div style="max-height:50vh;overflow-y:auto">
    <el-form
      label-width="120px"
      class="dialog-form"
      label-position="right"
      style="margin-bottom:15px"
    >
      <el-form-item label="上传图片">
        <el-upload
          ref="upload"
          accept=".jpg, .jpeg, .bmp, .png, .gif"
          name="file"
          list-type="picture-card"
          :auto-upload="true"
          :headers="headers"
          :file-list="fileList"
          :on-remove="del"
          :action="$util.getBaseUrl() + apiUrl"
          :before-upload="beforeUpload"
          :on-success="uploadSuccess"
          :on-error="uploadError"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="doUpload">确定</el-button>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    apiUrl: ""
  },
  data() {
    return {
      headers: {
        userid: localStorage.getItem("userid") || "",
        username: localStorage.getItem("username") || ""
      },
      imgUrl: location.protocol + "//" + location.host,
      urls: [],
      fileList: []
    };
  },
  methods: {
    initData(urls) {
      this.urls = urls;
      this.fileList = urls.map(item => {
        return { url: this.imgUrl + item };
      });
    },
    beforeUpload(file) {
      if (!this.$util.validFile(file, "image")) {
        this.$message({
          message: "上传图片格式不正确!",
          type: "error"
        });
        return false;
      }
      if (file.size / 1024 / 1024 > 200) {
        this.$message({
          message: "上传图片大小不能超过200MB!",
          type: "error"
        });
        return false;
      }
      return true;
    },
    uploadSuccess(res) {
      if (res.status == 200) {
        this.urls.push(res.message);
      } else {
        this.$message({
          message: res.message,
          type: "error"
        });
      }
    },
    uploadError(e) {
      this.$message({
        message: "上传失败",
        type: "error"
      });
    },
    del(file) {
      let index = this.urls.findIndex(el => {
        return file.url.substr(0, 4) == "http"
          ? this.imgUrl + el == file.url
          : el == file.response.message;
      });
      this.urls.splice(index, 1);
    },
    doUpload() {
      // if (this.urls.length < 1) {
      //   this.$message({
      //     message: "请上传图片",
      //     type: "warning"
      //   });
      //   return;
      // }
      this.$emit("upload", this.urls);
    }
  }
};
</script>
